package com.knowledge.service.impl;

import com.knowledge.entity.Article;
import com.knowledge.entity.User;
import com.knowledge.repository.ArticleRepository;
import com.knowledge.repository.UserRepository;
import com.knowledge.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional
    public Article createArticle(Article article, Long authorId) {
        User author = userRepository.findById(authorId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        article.setAuthor(author);
        return articleRepository.save(article);
    }

    @Override
    @Transactional
    public Article updateArticle(Long id, Article articleUpdate) {
        Article article = articleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("文章不存在"));
        
        article.setTitle(articleUpdate.getTitle());
        article.setContent(articleUpdate.getContent());
        article.setSummary(articleUpdate.getSummary());
        
        return articleRepository.save(article);
    }

    @Override
    @Transactional
    public void deleteArticle(Long id) {
        articleRepository.deleteById(id);
    }

    @Override
    public Article getArticle(Long id) {
        return articleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("文章不存在"));
    }

    @Override
    public Page<Article> getAllArticles(Pageable pageable) {
        return articleRepository.findAll(pageable);
    }

    @Override
    public Page<Article> getArticlesByAuthor(Long authorId, Pageable pageable) {
        return articleRepository.findByAuthorId(authorId, pageable);
    }

    @Override
    public Page<Article> searchArticles(String keyword, Pageable pageable) {
        return articleRepository.searchArticles(keyword, pageable);
    }

    @Override
    public Page<Article> getHotArticles(Pageable pageable) {
        return articleRepository.findHotArticles(pageable);
    }

    @Override
    @Transactional
    public Article incrementViewCount(Long id) {
        Article article = getArticle(id);
        article.setViewCount(article.getViewCount() + 1);
        return articleRepository.save(article);
    }

    @Override
    @Transactional
    public Article incrementLikeCount(Long id) {
        Article article = getArticle(id);
        article.setLikeCount(article.getLikeCount() + 1);
        return articleRepository.save(article);
    }
} 